<?php
// api/courses.php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit(0); }

require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];
$courseID = $_GET['CourseID'] ?? null;

switch($method) {
    case "GET":
        try {
            $sql = "SELECT c.*, d.DepartmentName
                    FROM Course c
                    LEFT JOIN Department d ON c.DepartmentID = d.DepartmentID";
            if ($courseID !== null) {
                $sql .= " WHERE c.CourseID = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$courseID]);
                $course = $stmt->fetch();
                if ($course) { echo json_encode($course); }
                else { http_response_code(404); echo json_encode(["error" => "Course not found"]); }
            } else {
                $sql .= " ORDER BY c.CourseName ASC";
                $stmt = $pdo->query($sql);
                $courses = $stmt->fetchAll();
                echo json_encode($courses);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(["error" => "Failed to retrieve courses", "details" => $e->getMessage()]);
        }
        break;

    case "POST":
        $data = json_decode(file_get_contents("php://input"), true);
        if (!isset($data['CourseName'], $data['Credit']) || empty(trim($data['CourseName'])) || !is_numeric($data['Credit'])) {
            http_response_code(400);
            echo json_encode(["error" => "Missing or invalid required fields (CourseName, Credit)"]);
            exit;
        }
        // DepartmentID is optional (can be NULL)
        $departmentID = isset($data['DepartmentID']) && $data['DepartmentID'] !== '' ? $data['DepartmentID'] : null;
        $description = $data['Description'] ?? null;

        try {
            $stmt = $pdo->prepare("INSERT INTO Course (CourseName, Credit, DepartmentID, Description) VALUES (?, ?, ?, ?)");
            $stmt->execute([trim($data['CourseName']), $data['Credit'], $departmentID, $description]);
            http_response_code(201);
            echo json_encode(["success" => true, "CourseID" => $pdo->lastInsertId()]);
        } catch (PDOException $e) {
            http_response_code(500);
             if ($e->getCode() == '23000') { // FK violation if DepartmentID is invalid
                 http_response_code(400);
                 echo json_encode(["error" => "Database constraint violation (e.g., invalid DepartmentID)", "details" => $e->getMessage()]);
             } else {
                 echo json_encode(["error" => "Failed to add course", "details" => $e->getMessage()]);
             }
        }
        break;

    case "PUT":
        if ($courseID === null) {
            http_response_code(400); echo json_encode(["error" => "CourseID is required for update"]); exit;
        }
        $data = json_decode(file_get_contents("php://input"), true);
        if (!isset($data['CourseName'], $data['Credit']) || empty(trim($data['CourseName'])) || !is_numeric($data['Credit'])) {
            http_response_code(400);
            echo json_encode(["error" => "Missing or invalid required fields (CourseName, Credit)"]);
            exit;
        }
        $departmentID = isset($data['DepartmentID']) && $data['DepartmentID'] !== '' ? $data['DepartmentID'] : null;
        $description = $data['Description'] ?? null;

        try {
            $stmt = $pdo->prepare("UPDATE Course SET CourseName = ?, Credit = ?, DepartmentID = ?, Description = ? WHERE CourseID = ?");
            $success = $stmt->execute([trim($data['CourseName']), $data['Credit'], $departmentID, $description, $courseID]);
            if ($success && $stmt->rowCount() > 0) {
                 echo json_encode(["success" => true, "message" => "Course updated"]);
            } elseif($success) {
                 http_response_code(404);
                 echo json_encode(["error" => "Course not found or no changes made"]);
            } else {
                 http_response_code(500);
                 echo json_encode(["error" => "Failed to update course"]);
            }
        } catch (PDOException $e) {
            http_response_code(500);
             if ($e->getCode() == '23000') { // FK violation if DepartmentID is invalid
                 http_response_code(400);
                 echo json_encode(["error" => "Database constraint violation (e.g., invalid DepartmentID)", "details" => $e->getMessage()]);
             } else {
                 echo json_encode(["error" => "Failed to update course", "details" => $e->getMessage()]);
             }
        }
        break;

    case "DELETE":
        if ($courseID === null) {
            http_response_code(400); echo json_encode(["error" => "CourseID is required for deletion"]); exit;
        }
        try {
            $stmt = $pdo->prepare("DELETE FROM Course WHERE CourseID = ?");
            $success = $stmt->execute([$courseID]);
             if ($success && $stmt->rowCount() > 0) {
                echo json_encode(["success" => true, "message" => "Course deleted"]);
            } else {
                http_response_code(404);
                echo json_encode(["error" => "Course not found"]);
            }
        } catch (PDOException $e) {
            if ($e->getCode() == '23000') { // Foreign key constraint violation (CourseOfferings)
                http_response_code(409);
                echo json_encode(["error" => "Cannot delete course: It is included in existing course offerings.", "details" => $e->getMessage()]);
            } else {
                http_response_code(500);
                echo json_encode(["error" => "Failed to delete course", "details" => $e->getMessage()]);
            }
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(["error" => "Method not allowed"]);
        break;
}
?>